import os
import sys

from modules.base import Base
from tests.upgrade_scene import UpgradeScene


def save_log(build_num, label, title, save_gausslog=False, compare_flag=False):
    base = Base()
    hosts = [kwargs.get('ipaddress'), kwargs.get('ipaddress_std1'),
             kwargs.get('ipaddress_std2')]
    username = base.sh('ls /home|grep upgrade_')
    passwd = kwargs.get('userpasswd')
    db_root_path = kwargs.get('db_root_path')
    parent_dir = f'/log/upgrade/{build_num}/{label}/{title}/'
    source_gausslog = f'{db_root_path}/{username}/gaussdb_log/{username}'
    gausslog_path = os.path.join(parent_dir, 'gausslog').strip()
    source_vmap = os.path.join(db_root_path, username, 'gaussdb_log', username,
                               'om', 'upgrade_checker',
                               'results').strip() + '/*'
    vmap_path = os.path.join(parent_dir, 'vmap').strip()

    cmd = f'mkdir -p {vmap_path};' \
          f'scp -r root@{hosts[0]}:{source_vmap} {vmap_path}'
    base.sh(cmd)

    base.log.info('-----校验各服务器是否有core产生-----')
    for ip in hosts:
        with base.ssh_connect(ip, 'root', passwd) as ssh:
            sftp = ssh.open_sftp()
            corefile = sftp.listdir('/core/corefile')
            sftp.close()
        if corefile:
            base.log.info(f'服务器{ip}有core文件，请检查！')
            base.log.info(corefile)
        else:
            base.log.info(f'服务器{ip}无core文件，请组织放心！')

    if compare_flag:
        for root, dirs, files in os.walk(os.path.join(os.getcwd(), 'diff')):
            for f in files:
                if f.endswith('.html'):
                    base.deal_with_diffhtml(os.path.join(root, f))
        diff_path = os.path.join(parent_dir, 'diff').strip()
        cmd = f'mkdir -p {diff_path};\n' \
              f'\\cp -r diff/* {diff_path}' \
              f'rm -rf diff/*'
        base.sh(cmd)

    if save_gausslog:
        cmd = f'mkdir -p {parent_dir}/gausslog;\n' \
              f'\\cp -r {source_gausslog}/* {gausslog_path}'
        for ip in hosts:
            with base.ssh_connect(ip, 'root', passwd) as ssh:
                base.ssh_run(ssh, cmd)

    runlog_path = os.path.join(parent_dir, 'run_log').strip()
    base.log.info(f'''
    -------------------------------------------------------------------------------------
    环境信息：{hosts}
    用户：{username}
    环境变量：source ~/gaussdb.bashrc
    元数据校验报告：{hosts[2]}:{vmap_path}
    GAUSSLOG见各节点：{gausslog_path}
    以上日志见：{hosts[2]}:{runlog_path}
    prometheus:http://10.243.209.200:9090/targets
    grafana:http://7.212.122.154:3000/
    -------------------------------------------------------------------------------------
    ''')
    cmd = f'mkdir -p {runlog_path};\n' \
          f'\\cp -r run.log {runlog_path};' \
          f'> run.log;'
    base.sh(cmd)


def run(func, build_num, label, title, *args):
    try:
        func(*args)
    except Exception as e:
        print(f'ERROR:{label}{title}')
        print(str(e))
        save_log(build_num, label, title, save_gausslog=True,
                 compare_flag=compare_flag)
    else:
        print(f'Success:{label}{title}')
        save_log(build_num, label, title, compare_flag=compare_flag)
    with open('run.log', 'w+', encoding='utf-8') as f:
        f.write('')


if __name__ == '__main__':
    for i in sys.argv:
        print(sys.argv.index(i), i)
    kwargs = dict()
    hostnames = f'{sys.argv[1]} {sys.argv[2]} {sys.argv[3]}'
    kwargs['ftp_root_path'] = sys.argv[4]
    kwargs['ftp_path'] = sys.argv[5]
    kwargs['git_link'] = sys.argv[6]
    kwargs['git_branch'] = sys.argv[7]
    kwargs['ipaddress'] = sys.argv[8]
    kwargs['ipaddress_std1'] = sys.argv[9]
    kwargs['ipaddress_std2'] = sys.argv[10]
    kwargs['userpasswd'] = sys.argv[11]
    kwargs['pkg_root_path'] = sys.argv[12]
    kwargs['db_root_path'] = sys.argv[13]
    kwargs['prefixPort'] = sys.argv[14]
    kwargs['tpcc_path'] = sys.argv[15]
    kwargs['upgrade_db_version'] = sys.argv[16]
    kwargs['upgrade_ftp_path'] = sys.argv[17]
    kwargs['upgrade_cm_flag'] = sys.argv[18]
    upgrade_scene = sys.argv[19]
    run_sql_case = sys.argv[20]
    build_number = sys.argv[21]
    kwargs['schds'] = sys.argv[22]
    run_data_compare = sys.argv[23]
    kwargs['ftp_vmap_path'] = sys.argv[24]

    upgrage_type = ''
    rollback_type = ''
    # 灰度升级
    if upgrade_scene == 'grey':
        upgrage_type = 'grey'
        rollback_type = 'non_rollback'
    # 就地升级
    elif upgrade_scene == 'inplace':
        upgrage_type = 'inplace'
        rollback_type = 'non_rollback'
    # 灰度升级--回滚
    elif upgrade_scene == 'grey_rollback':
        upgrage_type = 'grey'
        rollback_type = 'rollback'
    # 就地升级--回滚
    elif upgrade_scene == 'inplace_rollback':
        upgrage_type = 'inplace'
        rollback_type = 'rollback'
    # 灰度升级--强制回滚
    elif upgrade_scene == 'grey_force_rollback':
        upgrage_type = 'grey'
        rollback_type = 'force_rollback'
    # 就地升级--强制回滚
    elif upgrade_scene == 'inplace_force_rollback':
        upgrage_type = 'inplace'
        rollback_type = 'force_rollback'

    describe_prefix = ''
    run_sql_flag = True if run_sql_case.strip() == 'true' else False
    compare_flag = True if run_data_compare.strip() == 'true' else False

    tmp = ['ncm' if i == 'False' else 'cm' for i in
           kwargs['upgrade_cm_flag'].strip().split()]
    describe_prefix += '_'.join(tmp)
    if len(describe_prefix.split('_')) == describe_prefix.count('ncm'):
        describe_prefix = ''

    if rollback_type.strip() == 'non_rollback':
        if upgrage_type.strip() == 'grey':
            grey_flag = True
            up_des = '灰度升级'
        else:
            grey_flag = False
            up_des = '就地升级'
        describe = describe_prefix + up_des
        kwargs['scene_name'] = describe
        up_scene = UpgradeScene(*hostnames.split(), **kwargs)
        run(up_scene.auto_upgrade, build_number, up_scene.label,
            describe, grey_flag, run_sql_flag, compare_flag)
    else:
        if upgrage_type.strip() == 'grey':
            grey_flag = True
            up_des = '灰度升级'
        else:
            grey_flag = False
            up_des = '就地升级'
        if rollback_type.strip() == 'rollback':
            force_flag = False
            up_des += '_' + '回滚' + '_' + '升级提交'
        else:
            force_flag = True
            up_des += '_' + '强制回滚' + '_' + '升级提交'
        describe = describe_prefix + up_des
        kwargs['scene_name'] = describe
        up_scene = UpgradeScene(*hostnames.split(), **kwargs)
        print(kwargs['ftp_vmap_path'])
        run(up_scene.multi_rollback, build_number, up_scene.label,
            describe, grey_flag, force_flag, run_sql_flag, compare_flag)
